package com.waterfairy.getipsocket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ChangeDnsMasqSocketTool {
    private final static ChangeDnsMasqSocketTool CHANGE_DNS_MASQ_SOCKET_TOOL = new ChangeDnsMasqSocketTool();

    private final int PORT_START = 51200;

    public static ChangeDnsMasqSocketTool getInstance() {
        return CHANGE_DNS_MASQ_SOCKET_TOOL;
    }

    public void start() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                bindAndStart(PORT_START);
            }
        }.start();
    }

    private void bindAndStart(int port) {
        try {
            ServerSocket socketService = new ServerSocket(port);
            System.out.println("启动成功:" + port);
            while (true) {
                Socket socket = socketService.accept();
                InetAddress inetAddress = socket.getInetAddress();
                String hostAddress = inetAddress.getHostAddress();
                try {
                    //设置地址
                    boolean replaceIp1 = DnsMasq.getInstance().replaceIp("my.waterfairy.xyz", hostAddress);
                    boolean replaceIp2 = DnsMasq.getInstance().replaceIp("my.waterfairy.top", hostAddress);
                    if (replaceIp1 || replaceIp2) {
                        System.out.println("ip变化,重启 dnsmasq ");
                        //重启dns
                        Runtime.getRuntime().exec("docker restart dnsmasq");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("启动失败:" + port);
        }
    }
}
